<template>
  <Dialog
    v-model="dialogVisible"
    width="1200px"
    :title="
      typeIndex === 'add'
        ? t('article.add')
        : typeIndex === 'edit'
          ? t('article.edit')
          : t('article.detail')
    "
    :before-close="() => closeDialog(formRef)"
    :close-on-click-modal="true"
    maxHeight="780px"
  >
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="110px">
      <el-form-item :label="t('article.title')" class="w-95%" prop="title">
        <el-input
          v-model="form.title"
          :placeholder="t('article.titleMsg')"
          :disabled="!showButtons"
        />
      </el-form-item>
      <el-form-item :label="t('article.content')" class="w-95%" prop="content">
        <Editor v-model="form.content" :editorConfig="editorConfig" />
      </el-form-item>
      <el-form-item v-if="showButtons" :label="t('article.photo')" prop="photo" class="w-95%">
        <UploadFile
          class="w-100%"
          url="/common/uploadFile"
          drag
          :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'docx', 'doc', 'xlsx', 'xls']"
          :params="{ directory: 5 }"
          :limit="1"
          :fileListMap="picList"
          upload-file-button-name="点击上传或拖拽到此处上传"
          buttonWidth="100%"
          :button-link="true"
          :show-file-list="true"
          @upload-success-res="handleUploadCallback"
          @handle-remove-file="handleRemoveFile"
          @handle-picture-card-preview="handlePictureCardPreview"
        />
      </el-form-item>
      <el-form-item :label="t('article.type')" prop="type" class="w-95%">
        <el-select
          v-model="form.type"
          :filterable="true"
          :placeholder="t('article.type')"
          :clearable="false"
          :disabled="!showButtons"
        >
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('article.category')" prop="category" class="w-95%">
        <el-select
          v-model="form.category"
          :filterable="true"
          :placeholder="t('article.category')"
          :clearable="true"
          :disabled="!showButtons"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-show="7 == form.category"
        :label="t('article.pids')"
        class="w-95%"
        prop="pids"
      >
        <el-input
          v-model="productsDisplayText"
          disabled
          :placeholder="'请选择' + t('article.pids')"
        >
          <template #append>
            <el-button size="small" text type="primary" @click="handleOpenMining">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item :label="t('article.publish_date')" class="w-95%" prop="publish_date">
        <el-date-picker
          v-model="form.publish_date"
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          :placeholder="'请选择' + t('article.publish_date')"
          style="width: 100%"
          :disabled="!showButtons"
        />
      </el-form-item>
    </el-form>
    <template v-if="showButtons" #footer>
      <el-button class="m-r-4" @click="closeDialog(formRef)">{{ t('common.cancel') }} </el-button>
      <el-button type="primary" @click="submit(formRef)">{{ t('common.save') }} </el-button>
    </template>

    <DialogProduct
      ref="DialogProductRef"
      @expose-multiple-data="getExposeProductData"
      :multiple="true"
      :pagination="false"
    />
  </Dialog>
</template>
<script setup lang="ts">
import { createImageViewer } from '@/components/ImageViewer'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
import { getarticleAddApi, getarticleEditApi, getEnumApi } from '@/api/article'
import DialogProduct from '@/components/Dialog/src/Product.vue'
const emit = defineEmits(['refresh'])
import type { IEditorConfig } from '@wangeditor/editor'
const { t } = useI18n()

const dialogVisible = ref<boolean>(false)
const showButtons = ref<boolean>(true)
const typeList = ref<Array<Record<string, any>>>([])
const categoryList = ref<Array<Record<string, any>>>([])
const productsDisplayText = ref('')

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  typeList.value = resp.data.type
  categoryList.value = resp.data.category
}
const typeIndex = ref<string>()

const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  title: '',
  content: '',
  photo: '',
  type: '',
  category: '',
  publish_date: '',
  pids: ''
})
// 表单验证规则
const rules = ref<FormRules>({
  title: [
    {
      required: true,
      message: t('article.titleRequired'),
      trigger: ['blur']
    }
  ],
  content: [
    {
      required: true,
      message: t('article.contentRequired'),
      trigger: ['blur']
    }
  ],
  type: [
    {
      required: true,
      message: t('article.typeRequired'),
      trigger: ['blur']
    }
  ],
  photo: [
    {
      required: true,
      message: t('article.photolInvalid'),
      trigger: ['blur', 'change']
    }
  ],
  pids: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (form.value.category == 7) {
          if (!value || value.trim() === '') {
            callback(new Error('当分类为Machines Firmware Update时，必须选择关联矿机'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: ['blur', 'change']
    }
  ]
})

const DialogProductRef = ref<any>(null)

const handleOpenMining = () => {
  console.log('form.value.pids', form.value.pids)
  nextTick(() => {
    DialogProductRef!.value!.dialogVisible = true
    // 将pids字符串拆分成对象数组
    const selectedProducts = form.value.pids
      ? form.value.pids.split(',').map((id: string) => ({ id: parseInt(id.trim()) }))
      : []
    DialogProductRef!.value!.initialize(selectedProducts)
  })
}

const getExposeProductData = (val: any) => {
  form.value.pids = val.map((item: any) => item.id).join(',')
  productsDisplayText.value = val.map((item: any) => item.cname).join(',')
}

// 编辑器配置
const editorConfig: IEditorConfig = {
  placeholder: '请输入内容...',
  readOnly: false,
  autoFocus: false,
  scroll: true,
  customAlert: (info: string, type: 'success' | 'info' | 'warning' | 'error') => {
    ElMessage[type](info)
  },
  maxLength: 100000,
  customPaste: undefined, // 或提供自定义粘贴处理函数
  onCreated: undefined, // 或提供创建回调
  onChange: undefined, // 或提供变更回调
  onDestroyed: undefined, // 或提供销毁回调
  onFocus: undefined, // 或提供聚焦回调
  onBlur: undefined, // 或提供失焦回调
  onMaxLength: undefined, // 或提供超出长度回调
  MENU_CONF: {
    uploadImage: {
      server: `${import.meta.env.VITE_API_BASE_PATH}/common/uploadFile`,
      fieldName: 'file',
      maxFileSize: 10 * 1024 * 1024,
      maxNumberOfFiles: 10,
      allowedFileTypes: ['image/*'],
      meta: {
        folder: 'editor-images',
        directory: 2
      },
      onBeforeUpload: (file: File) => {
        console.log('上传前:', file)
        return file
      },
      onSuccess: (file: File, res: any) => {
        // 处理返回结果
        if (res.code === 0) {
          // 注意这里改为 0
          return {
            url: res.data.url, // 返回图片 URL
            alt: res.data.name || file.name, // 图片文字说明
            href: res.data.url // 点击图片跳转的链接，可选
          }
        } else {
          // 抛出错误会触发 onError
          throw new Error(res.message || '上传失败')
        }
      },
      onError: (file: File, err: Error, res?: any) => {
        console.error('上传失败:', err)
      }, // 自定义插入图片
      customInsert: (res: any, insertFn: any) => {
        // res 即上面 onSuccess 的返回结果
        console.log('customInsert res:', res)
        insertFn(res.data.url, res.data.alt, res.data.href)
      }
    }
  }
}

const picList = ref<any[]>([])
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 实际项目中替换为API调用
        console.log('fileObj', fileObj.value, form.value)
        console.log('form', form.value)

        const resp =
          typeIndex.value === 'add'
            ? await getarticleAddApi(form.value)
            : await getarticleEditApi(form.value)

        // 模拟API响应
        // const resp = { code: 0 }

        if (resp.code === 0) {
          ElMessage.success(
            typeIndex.value === 'add' ? t('article.createSuccess') : t('article.updateSuccess')
          )
          closeDialog(formEl)
          emit('refresh')
        }
      } catch (error) {
        console.error('文章提交失败', error)
      }
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return

  // 清除表单数据
  form.value = {
    title: '',
    content: '',
    photo: '',
    type: '',
    category: '',
    publish_date: '',
    pids: ''
  }

  // 清除产品相关数据
  productsDisplayText.value = ''

  // 清除文件相关数据
  fileObj.value = null
  picList.value = []

  // 重置表单验证状态
  formEl.resetFields()

  // 关闭弹窗
  dialogVisible.value = false
}

const getBackShow = (type: string, row?: Record<string, any>) => {
  typeIndex.value = type
  editorConfig.readOnly = typeIndex.value == 'detail'
  showButtons.value = true
  picList.value = []
  console.log('row', row)
  getDropDownBoxInfo()
  if (type === 'edit' || type === 'detail') {
    if (type === 'detail') {
      showButtons.value = false
    }
    form.value = row!
    if (form.value.photo) {
      picList.value = [
        {
          name: form.value.name,
          id: form.value.photoId,
          url: form.value.photoUrl
        }
      ]
      fileObj.value = {
        name: form.value.name,
        id: form.value.photoId,
        url: form.value.photoUrl
      }
    }
    if (form.value.pids_name) {
      productsDisplayText.value = form.value.pids_name
    }
  }
}

defineExpose({
  dialogVisible,
  getBackShow
})
//上传成功以后回调
const fileObj = ref<any>(null)
const handleUploadCallback = (val: any) => {
  console.log('val', val)
  fileObj.value = val
  form.value.photo = fileObj.value ? fileObj.value.id : ''
}

const handleRemoveFile = (val: any) => {
  fileObj.value = null
  form.value.photo = fileObj.value ? fileObj.value.id : ''
}

const handlePictureCardPreview = (url: any) => {
  try {
    if (!url) return
    if (/\.(jpg|jpeg|png|gif|bmp)$/i.test(url))
      return createImageViewer({
        urlList: [url]
      })
    window.open(url)
  } catch (error) {
    console.error('预览图片失败:', error)
  }
}
</script>
<style lang="less" scoped>
.m-r-4 {
  margin-right: 16px;
}
</style>
